package com.wan37.logic.handler.message;

import com.wan37.logic.component.Worker;
import com.wan37.logic.domain.vo.MessageVO;
import com.wan37.logic.global.reference.SpringContextHolder;
import com.wan37.logic.handler.LogicServerHandler;
import com.wan37.logic.handler.MsgHandler;
import com.wan37.logic.listener.EventDispatcher;
import com.wan37.logic.listener.event.EventType;
import com.wan37.logic.listener.event.user.UserLogoutEvent;
import com.wan37.logic.service.cache.UserServiceCache;
import com.wan37.protobuf.constant.PtoNum;
import com.wan37.protobuf.message.client2server.game.Game;
import com.wan37.protobuf.message.internal.Internal;
import com.wan37.protobuf.util.ServerProtoUtils;
import io.netty.buffer.ByteBuf;

/**
 * @author : luoyong
 * @date : 2020-06-24 15:00
 **/
public class GateUserLogoutHandler extends MsgHandler {
    private UserServiceCache userServiceCache;

    /**
     * MsgHandler构造函数
     *
     * @param messageVO
     */
    public GateUserLogoutHandler(MessageVO messageVO) {
        super(messageVO);
        this.userServiceCache = SpringContextHolder.getBean("userServiceCache");
    }

    @Override
    public void execute(Worker worker) throws Exception {
        Game.GGameUserLogoutMsg gGameUserLogoutMsg = (Game.GGameUserLogoutMsg) messageVO.getMessage();
        String userId = gGameUserLogoutMsg.getSenderId();

        EventDispatcher.getInstance().fireEvent(new UserLogoutEvent(EventType.LOGOUT, userId));

        //将用户从列表中删除
        userServiceCache.getUserServiceMap().remove(userId);

        ByteBuf byteBuf = ServerProtoUtils.pack2Server(Internal.DestType.Gate,
                messageVO.getNetId(), userId, PtoNum.GGAMEUSERLOGOUTMSG, gGameUserLogoutMsg);
        LogicServerHandler.getGateConnCtx().writeAndFlush(byteBuf);
    }
}
